/**
 * 绘制svg图的逻辑
 * @type {number}
 */


var x_init = 50;  // 初始X坐标
var y_init = 170; // 初始Y坐标
var node_dist = 20;  // 节点间距
var node_height = 38;  // 节点高度

var graph_width_node = 100;
var graph_height = 250;
var graph;
var graph_width;
var senDataNodes;

function DrawGraph(dataJson, parentClassName, optionObj) {
    graph = cloneObj(dataJson);
    senDataNodes = graph.items;
    graph_width = senDataNodes.length * graph_width_node + 50;
    // 新建一个svg
    var svg = d3.select("." + parentClassName)
        .append("svg")
        .attr("class", "sentence_svg")
        .attr("width", graph_width)
        .attr("height", graph_height);
    // load data and draw graph
//    d3.json(url, function(error, graph) {
    // Adjust Nodes
    senDataNodes = AdjustNodesPosition(senDataNodes);
    // append <g>
    var g = svg.selectAll(".node")
        .data(senDataNodes)
        .enter()
        .append("g");
    // append <rect>
    var node = g.append("rect")
        .attr("class", "layui-btn term")
        .attr("fill", function (e) {
            return "#" + getColorClassName(e.pos.charAt(0));
        })
        .attr("data-word", function (e) {
            return e.word;
        })
        .attr("x", function (e) {
            return e.x;
        })
        .attr("y", function (e) {
            return e.y;
        })
        .attr("width", function (e) {
            return e.w;
        })
        .attr("height", function (e) {
            return e.h;
        });
    // append <text> word
    var text = g.append("text")
        .text(function (e) {
            return e.word;
        })
        .attr("class", "sen_word")
        .attr("x", function (e) {
            return e.x + (e.w - BytesLength(e.word) * 8) / 2;
        })
        .attr("y", function (e) {
            return e.y + 24;
        });
    // 词性标注
    if (optionObj.pos) {
        var pos = g.append("text")
            .text(function (e) {
                return getPosLevel_1(e.pos);
            })
            .attr("class", "pos")
            .attr("fill", "#678f80")
            .attr("x", function (e) {
                return e.x + (e.w - BytesLength(e.word) * 8) / 2;
            })
            .attr("y", function (e) {
                return e.y + 58;
            });
    }

    if (optionObj.entity) {
        var pos = g.append("text")
            .text(function (e) {
                if (e.pos.charAt(0) == "n" && (e.pos.length > 1))
                    return getPosLevel_2(e.pos);
                else
                    return "";
            })
            .attr("class", "pos")
            .attr("fill", "#678f80")
            .attr("x", function (e) {
                return e.x + (e.w - BytesLength(e.word) * 8) / 2;
            })
            .attr("y", function (e) {
                if (optionObj.pos)
                    return e.y + 77;
                else
                    return e.y + 58;
            });
    }
    if (optionObj.dependency) {
        //新建一个关系链
        var links = new Array();
        for (var i = 0; i < senDataNodes.length; i++) {

            if (optionObj.remap.get(senDataNodes[i].deprel)) {

                var obj = new Object();
                obj.source = parseInt(senDataNodes[i].id) - 1;
                if (parseInt(senDataNodes[i].head) != 0)
                    obj.target = parseInt(senDataNodes[i].head) - 1;
                else
                    obj.target = senDataNodes[i].head;
                obj.relation = senDataNodes[i].detail;
                links.push(obj);
            }
        }


        // 配置箭头
        ConfigArrow4Svg(svg);
        // append links
        var path = svg.selectAll(".link")
            .data(links)
            .enter()
            .append("path")
            .attr("d", function (e) {
                return LineFunction(e);
            })
            .attr("data-relation", function (e) {
                return e.relation;
            })
            .attr("data-from", function (e) {
                return e.source;
            })
            .attr("data-to", function (e) {
                return e.target;
            })
            .attr("class", "link")
            .attr("marker-end", "url(#arrowhead)");

        // append link relation
        var relation = svg.selectAll(".text")
            .data(links)
            .enter()
            .append("text")
            .attr("class", "sentence_speech_en")
            .attr("data-from", function (e) {
                return e.source;
            })
            .attr("data-to", function (e) {
                return e.target;
            })
            .attr("data-relation", function (e) {
                return e.relation;
            })
            .text(function (e) {
                return e.relation;
            })
            .attr("x", function (e) {
                return e.mid_x - 12;
            })
            .attr("y", function (e) {
                return e.mid_y + 10;
            });

    }

    // LineFunction defin
    function LineFunction(e) {
        var node_source = senDataNodes[e.source];
        var node_target = senDataNodes[e.target];
        var x_beg = node_source.x + node_source.w / 2;
        var x_end = node_target.x + node_target.w / 2;
        var y = node_source.y;
        var direction = 0; // 0:left=>right, 1:right=>left
        if (x_beg > x_end) {
            direction = 1;
        }
        var dist = direction == 0 ? e.target - e.source : e.source - e.target;

        var x_len = direction == 0 ? x_end - x_beg : x_beg - x_end;
        // adjust begin position
        if (direction == 0) {
            x_beg += 10 - dist * 2;
        } else {
            x_beg -= 10 - dist * 2;
        }

        // decide mid position
        var x_mid = 0;
        // ---- left => right
        if (direction == 0) {
            x_mid = x_beg + x_len / 2;
        } else {
            x_mid = x_beg - x_len / 2;
        }

        var y_mid = y_init - dist * 20;
        if (y_mid <= 0) {
            y_mid = 10;
        }
        e.mid_x = x_mid;
        e.mid_y = y_mid;

        var d = "M" + x_beg + "," + y + " ";
        d += "A" + x_len / 2 + " " + (y - y_mid) + " 0 0 " + (1 - direction) + " " + x_end + " " + y;
        return d;
    }

    //}) ;
}

function BytesLength(str) {
    return str.replace(/[^\x00-\xff]/gi, "--").length;
}

// input nodes : 节点数组
// 根据宽度, 添加坐标以及宽高信息 (用于Rect绘制)
function AdjustNodesPosition(nodes) {
    for (var i = 0; i < nodes.length; i++) {
        if (i == 0) {
            nodes[i].x = x_init;
        } else {
            nodes[i].x = parseInt(nodes[i - 1].x) + nodes[i - 1].w + node_dist;
        }
        nodes[i].y = y_init;
        nodes[i].w = BytesLength(nodes[i].word) * 15 + 20;  // 一个字节宽度8px, 预留边框20PX
        nodes[i].h = node_height;
    }
    return nodes;
}

function ConfigArrow4Svg(svg) {
    svg.append("defs").append("marker")
        .attr("id", "arrowhead")
        .attr("viewBox", "0 -5 10 10")
        .attr("refX", 10)
        .attr("markerWidth", 6)
        .attr("markerHeight", 10)
        .attr("orient", "auto")
        .append("svg:path")
        .attr("fill", "#1a9300")
        .attr("d", "M0,-5L10,0L0,5");
}


/**
 * 页面逻辑
 */
//展示可以点击查看全图的提示
function showFullSvgTips() {

    var layer = layui.layer;
    layer.tips('您可以点击眼睛，全屏查看矢量图', '.eye-tips', {
        tips: [1, '#3595CC'],
        time: 4000
    });
}

//大图展示svg
function showFullSvg(node) {
    var view = node.parent().parent().parent().parent().find('.panel-collapse');
    var data = "<div style='position:absolute; top:35%; '>" + view[0].innerHTML + "</div>";
    var index = layer.open({
        type: 1,
        title: "全屏查看SVG",
        content: data,
        area: ['320px', '195px'],
        maxmin: true
    });
    layer.full(index);
}


//监听需求改变的事件
$('body').on("click", ".layui-form-checkbox", function () {

    onOptionChange();
});

function onOptionChange() {

    if (reviceData.length == 0)
        return;
    var index = layer.load(2);
    var option = getOptionObj();

    //重新绘图并加载到页面上
    for (var i = 0; i < reviceData.length; i++) {
        $(".div_sen_depen_draw_" + i).empty();
        var dataObj = reviceData[i];
        DrawGraph(dataObj, "div_sen_depen_draw_" + i, option);
    }
    layer.close(index);
}

//返回一个需求的obj
function getOptionObj() {
    var option = new Object();
    var short_sen = $('body').find('input[name="check_pos"]').next().hasClass('check_short_sentences');
    var pos = $('body').find('input[name="check_pos"]').next().hasClass('layui-form-checked');
    var entity = $('body').find('input[name="check_entity"]').next().hasClass('layui-form-checked');
    var dependency = $('body').find('input[name="check_show_dependency"]').next().hasClass('layui-form-checked');
    var isHave_denpendcy = $('body').find('input[name="check_isHave_denpendcy"]').next().hasClass('layui-form-checked');

    var reMap = new Map();
    reMap.set('SBV', $('body').find('input[name="SBV"]').next().hasClass('layui-form-checked'));
    reMap.set('VOB', $('body').find('input[name="VOB"]').next().hasClass('layui-form-checked'));
    reMap.set('IOB', $('body').find('input[name="IOB"]').next().hasClass('layui-form-checked'));
    reMap.set('FOB', $('body').find('input[name="FOB"]').next().hasClass('layui-form-checked'));
    reMap.set('DBL', $('body').find('input[name="DBL"]').next().hasClass('layui-form-checked'));
    reMap.set('ATT', $('body').find('input[name="ATT"]').next().hasClass('layui-form-checked'));
    reMap.set('ADV', $('body').find('input[name="ADV"]').next().hasClass('layui-form-checked'));
    reMap.set('CMP', $('body').find('input[name="CMP"]').next().hasClass('layui-form-checked'));
    reMap.set('COO', $('body').find('input[name="COO"]').next().hasClass('layui-form-checked'));
    reMap.set('POB', $('body').find('input[name="POB"]').next().hasClass('layui-form-checked'));
    reMap.set('LAD', $('body').find('input[name="LAD"]').next().hasClass('layui-form-checked'));
    reMap.set('RAD', $('body').find('input[name="RAD"]').next().hasClass('layui-form-checked'));
    reMap.set('IS', $('body').find('input[name="IS"]').next().hasClass('layui-form-checked'));
    reMap.set('WP', $('body').find('input[name="WP"]').next().hasClass('layui-form-checked'));
    reMap.set('HED', $('body').find('input[name="HED"]').next().hasClass('layui-form-checked'));


    option.pos = pos;
    option.entity = entity;
    option.dependency = dependency;
    option.isHave_denpendcy = isHave_denpendcy;
    option.remap = reMap;
    return option;
}


/**
 * 下面是异步逻辑部分
 *
 * @type {Set<any>}
 */
//关系的集合
var reList = new Set();
//记录上一个被点击的临时变量
var segLastClickTmpID = "temp";
//记录目前已经有的数据
var reviceData = new Array();

//监听文本框事件
$('#text_main_text').bind('input', function () {
    var before = $('#text_main_text').val();
    TextWordCount(2000, "text_main_text");
    setTimeout(function (args) {
        var after = $('#text_main_text').val();
        if (before == after && after.trim() != '') {
            doTextChange();
        }
    }, 2000);

});

function doTextChange() {

    //加载等待
    var index = layer.load(2, {shade: 0.25});

    //查看是否要使用队列来发送请求
    var check_short_sentences = $('body').find('input[name="check_short_sentences"]').next().hasClass('layui-form-checked');
    if (check_short_sentences == true) {
        var text = $('#text_main_text').val();
        text = $.trim(text);
        var each = text.split("。");
        for (var j = 0; j < each.length; j++) {
            if (each[j] == "")
                each.splice(j, 1);
        }
        var currentIndex = 0;
        eachSentence();

        function eachSentence() {
            if (currentIndex >= each.length) {
                return;
            }
            //创建一个js对象
            var requestObj = new Object();
            //填充对象信息
            requestObj.text = each[currentIndex];
            // 对象转换为字符串
            var requestJson = JSON.stringify(requestObj);
            //发送异步请求
            jQuery.ajax({
                url: sen_single_path,
                type: "post",
                data: requestJson,
                dataType: "json",
                contentType: "application/json;charset=utf-8"
            }).done(function (data) {

                //将结果加载到页面中
                if (currentIndex == 0) {
                    reviceData.splice(0, reviceData.length);//清空数组
                    loadSenMes(0, data.data, true);
                }
                else {
                    loadSenMes(currentIndex, data.data, false);
                }
                //更新关系选择栏
                loadRelationBar(data.data.items);
                //存放到数据集合中，以便重绘
                reviceData.push(data.data);
                currentIndex++;
                //digui
                eachSentence();
            }).fail(function (data) {
                layer.alert("请求失败", {icon: 7});
                layer.close(index);
                //递归
                currentIndex++;
                eachSentence();
            });

        }


        //关闭等待层
        layer.close(index);

    }
    else {

        //创建一个js对象
        var requestObj = new Object();
        //获取文本库内容
        var text = $('#text_main_text').val();
        //去空哥
        text = $.trim(text);
        //填充对象信息
        requestObj.text = text;
        // 对象转换为字符串
        var requestJson = JSON.stringify(requestObj);

        //发送异步请求
        jQuery.ajax({
            url: sen_single_path,
            type: "post",
            data: requestJson,
            dataType: "json",
            contentType: "application/json;charset=utf-8"
        }).done(function (data) {
            //关闭等待层
            layer.close(index);
            //将结果加载到页面中
            loadSenMes(0, data.data, true);
            //更新关系选择栏
            loadRelationBar(data.data.items);
            //存放到数据集合中，以便重绘
            reviceData.splice(0, reviceData.length);//清空数组
            reviceData.push(data.data);
            // console.log(data);
        }).fail(function (data) {
            layer.alert("请求失败", {icon: 7});
            layer.close(index);
        });
    }


    //加载XML视图
    loadXMLView();

    function loadXMLView() {
        //创建一个js对象
        var requestObj = new Object();
        //获取文本库内容
        var text = $('#text_main_text').val();
        //去空哥
        text = $.trim(text);
        //填充对象信息
        requestObj.text = text;
        requestObj.format = "xml";
        // 对象转换为字符串
        var requestJson = JSON.stringify(requestObj);
        //发送异步请求
        jQuery.ajax({
            url: sen_single_path,
            type: "post",
            data: requestJson,
            dataType: "text",
            contentType: "application/json;charset=utf-8"
        }).done(function (data) {
            //关闭等待层
            layer.close(index);
            $("#code_xml").text(formatXml(data.toString()));
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }).fail(function (data) {
            layer.alert("请求失败", {icon: 7});
            layer.close(index);
        });


    }

    //加载Json视图
    loadJsonView();

    function loadJsonView() {
        //创建一个js对象
        var requestObj = new Object();
        //获取文本库内容
        var text = $('#text_main_text').val();
        //去空哥
        text = $.trim(text);
        //填充对象信息
        requestObj.text = text;
        requestObj.format = "json";
        // 对象转换为字符串
        var requestJson = JSON.stringify(requestObj);
        //发送异步请求
        jQuery.ajax({
            url: sen_single_path,
            type: "post",
            data: requestJson,
            dataType: "json",
            contentType: "application/json;charset=utf-8"
        }).done(function (data) {
            //关闭等待层
            layer.close(index);
            $("#code_json").text(formatJson(data));
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }).fail(function (data) {
            layer.alert("请求失败", {icon: 7});
            layer.close(index);
        });

    }

    //加载句法分析的信息到百叶窗
    function loadSenMes(num, data, isAppend) {

        var parent = $('#accordion');
        //判断是否要清空之前所有的句法分析模块的信息
        if (isAppend) {
            parent.empty();
        }
        //加到页面中
        parent.append(getEachSentenceStr(num, data));
        //绘图
        var option = getOptionObj();
        DrawGraph(data, "div_sen_depen_draw_" + num, option);


    }


    //获取动态生成的长串
    function getEachSentenceStr(num, data) {
        return "<div class=\"panel panel-default\">" +
            "  <div class=\"panel-heading\" role=\"tab\" id=\"heading_" + num + "\">" +
            "    <h4 class=\"panel-title\">" +
            "      <a role=\"button\" data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse_" + num + "\" aria-expanded=\"true\" aria-controls=\"collapse_" + num + "\">" +
            data.text +
            "        <i class=\"fa fa-eye\" aria-hidden=\"true\" onclick=\"showFullSvg($(this))\"></i></a>" +
            "    </h4>" +
            "  </div>" +
            "  <div id=\"collapse_" + num + "\" class=\"panel-collapse collapse in\" role=\"tabpanel\" aria-labelledby=\"heading_" + num + "\">" +
            "    <div class=\"panel-body div_sen_depen_draw_" + num + "\"></div>" +
            "  </div>" +
            "</div>";
    }


    //载入关系栏目
    function loadRelationBar(data) {
        var parent = $('#div_sen_denp_relation');
        parent.empty();
        var items = data;
        var relationSet = new Set();
        for (var i = 0; i < items.length; i++) {
            relationSet.add(items[i].detail);
        }

        for (var p of relationSet) {
            var re = getSenRelation(p);
            parent.append("<input type=\"checkbox\" name=\"" + re + "\" title=\"" + p + "\"  checked onclick=\"onOptionChange()\">");
        }
        //渲染
        layui.form.render();
        layui.element.init();
    }

    //根据选定的关系重回

}


/**
 *
 * 下面是文件上传与结果处理部分
 * @type {Map<any, any>}
 */
//文件上传的MAp
var fileIdMap = new Map();

layui.use('layedit', function () {
    var element = layui.element;

    //获取hash来切换选项卡，假设当前地址的hash为lay-id对应的值
    var layid = location.hash.replace(/^#test1=/, '');
    element.tabChange('test1', layid); //假设当前地址为：http://a.com#test1=222，那么选项卡会自动切换到“发送消息”这一项

    //监听Tab切换，以改变地址hash值
    element.on('tab(test1)', function () {
        location.hash = 'test1=' + this.getAttribute('lay-id');
    });

    /**
     * API TAB切换
     *
     * api-tab是lay-filter
     */
        //触发事件
    var element = layui.element;

    var active = {
        tabAdd: function () {
            var count = $('#div_api_tab').children('ul').children('li').length;
            var newID = getMD5Id();
            if (count < 10) {
                //新增一个Tab项
                element.tabAdd('api-tab', {
                    title: '样例' + (count + 1) + '<span class="layui-badge-dot"></span>'  //用于演示
                    , content: getAnewAPITab(newID)
                    , id: newID//实际使用一般是规定好的id，这里以时间戳模拟下
                })
                layui.form.render();
                layui.element.init();

            }
            else {
                layer.msg('求求你别点了,最多只能打开10个好吧！');
            }
        }
    };

    //取消小红点
    $('.layui-tab-title').click(function () {
        $('.layui-this').children('.layui-badge-dot').remove();
    });

    $('.site-demo-active').on('click', function () {
        var othis = $(this), type = othis.data('type');
        active[type] ? active[type].call(this, othis) : '';
    });

});

layui.use('upload', function () {
    var $ = layui.jquery
        , upload = layui.upload;

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#test1'
        , url: '/upload/'
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        , done: function (res) {
            //如果上传失败
            if (res.code > 0) {
                return layer.msg('上传失败');
            }
            //上传成功
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadInst.upload();
            });
        }
    });

    //多图片上传
    upload.render({
        elem: '#test2'
        , url: '/upload/'
        , multiple: true
        , before: function (obj) {
            //预读本地文件示例，不支持ie8
            obj.preview(function (index, file, result) {
                $('#demo2').append('<img src="' + result + '" alt="' + file.name + '" class="layui-upload-img">')
            });
        }
        , done: function (res) {
            //上传完毕
        }
    });

    //同时绑定多个元素，并将属性设定在元素上
    upload.render({
        elem: '.demoMore'
        , before: function () {
            layer.tips('接口地址：' + this.url, this.item, {tips: 1});
        }
        , done: function (res, index, upload) {
            var item = this.item;
            console.log(item); //获取当前触发上传的元素，layui 2.1.0 新增
        }
    })


    //拖拽上传
    var uploadDrag = upload.render({
        elem: '#single-file'
        , url: sen_file_upload_path
        , accept: 'file' //普通文件
        , exts: 'txt|doc' //txt
        , size: 4086 //kb
        , before: function (obj) {
            // layer.msg('图片上传中', {
            //     icon: 16
            //     , shade: 0.01
            // });
        }
        , done: function (res) {
            console.log(res)
            //如果正常返回
            if (res.status == 0) {
                var index = layer.load(2);
                showFileSenResult(res);
                layer.close(index);
            }
            else {
                layer.alert('该文件异常，请重新上传', {
                    icon: 2,
                    skin: 'layer-ext-moon'
                })
            }
        }
        , error: function () {
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-mini demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function () {
                uploadDrag.upload();
            });
        }
    });


    //多文件列表示例
    var demoListView = $('#demoList')
        , uploadListIns = upload.render({
        elem: '#testList'
        , url: sen_file_upload_path
        , accept: 'file'
        , exts: 'txt|doc' //txt
        , multiple: true
        , auto: false
        , bindAction: '#ListAction'
        , choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1014).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-mini demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-mini layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    uploadListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });

                demoListView.append(tr);
            });
        }
        , done: function (res, index, upload) {
            //关闭加载层
            layer.closeAll('loading');

            if (res.status == 0) { //上传成功
                var tr = demoListView.find('tr#upload-' + index)
                    , tds = tr.children();
                var thisID = $.trim(getMD5Id());

                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html("<button id=\"" + thisID + "\" class=\"layui-btn layui-btn-mini\" onclick=\"showFileSenResultByID(\'" + thisID + "\')\">查看</button>");
                //将结果用map存储
                fileIdMap.set(thisID, res);
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            }
            this.error(index, upload);

            //关闭加载层
            layer.closeAll('loading');
        }
        , error: function (index, upload) {
            var tr = demoListView.find('tr#upload-' + index)
                , tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
            //关闭加载层
            layer.closeAll('loading');
        }
    });


});

//文件上传加载层
function mutifileLoad() {

    layer.load(2);
}

function showFileSenResult(res) {


    var thisData = res.data[0].senResult;
    var tmpStr = "";
    var fileName = res.data[0].fileName;
    var downloadPath = res.data[0].download;
    var num = getMD5Id();
    //取出分析的结果
    tmpStr = "<div class=\"panel panel-default\">" +
        "  <div class=\"panel-heading\" role=\"tab\" id=\"heading_" + num + "\">" +
        "    <h4 class=\"panel-title\">" +
        "      <a role=\"button\" data-toggle=\"collapse\" data-parent=\"#accordion\" href=\"#collapse_" + num + "\" aria-expanded=\"true\" aria-controls=\"collapse_" + num + "\">" +
        "        <i class=\"fa fa-eye\" aria-hidden=\"true\" onclick=\"showFullSvg($(this))\"></i></a>" +
        "    </h4>" +
        "  </div>" +
        "  <div id=\"collapse_" + num + "\" class=\"panel-collapse collapse in\" role=\"tabpanel\" aria-labelledby=\"heading_" + num + "\">" +
        "    <div class=\"panel-body div_sen_depen_draw_" + num + "\"></div>" +
        "  </div>" +
        "</div>";

    var resStr = "";
    resStr += '<fieldset class="layui-elem-field"><legend>句法分析结果集合</legend> <div class="layui-field-box"><fieldset class="layui-elem-field layui-field-title"><legend>文件原文</legend><div class="layui-field-box"><blockquote class="layui-elem-quote  layui-quote-nm">' + thisData.text + '</blockquote></div></fieldset> <fieldset class="layui-elem-field layui-field-title"><legend>句法分析结果</legend><div class="layui-field-box"></div></fieldset><div class="layui-row"> <div class="layui-col-md12"> ' + tmpStr +
        '</div></div><fieldset class="layui-elem-field layui-field-title"><legend>结果操作</legend><div class="layui-field-box"><div class="layui-btn-container">' +
        '<a href=/' + downloadPath + ' download=' + fileName + ' class="layui-btn"><i class="layui-icon">&#xe601;</i> 下载文件</a> </div></div><blockquote class="layui-elem-quote">注:本处句法分析结果以TXT形式保存。</blockquote></fieldset></div></fieldset>';

    //弹出窗口
    layer.open({
        type: 1,
        title: fileName + '句法结果展示',
        shade: 0,
        maxmin: true,
        skin: 'layui-layer-rim', //加上边框
        area: ['840px', '480px'], //宽高
        content: resStr
    });

    //打开全部绘制选项
    var option = new Object();
    var reMap = new Map();
    reMap.set('SBV', true);
    reMap.set('VOB', true);
    reMap.set('IOB', true);
    reMap.set('FOB', true);
    reMap.set('DBL', true);
    reMap.set('ATT', true);
    reMap.set('ADV', true);
    reMap.set('CMP', true);
    reMap.set('COO', true);
    reMap.set('POB', true);
    reMap.set('LAD', true);
    reMap.set('RAD', true);
    reMap.set('IS', true);
    reMap.set('WP', true);
    reMap.set('HED', true);

    option.pos = true;
    option.entity = true;
    option.dependency = true;
    option.isHave_denpendcy = true;
    option.remap = reMap;
    DrawGraph(thisData, "div_sen_depen_draw_" + num, option);


}

function showFileSenResultByID(ID) {

    var res = fileIdMap.get(ID);
    if (res == null) {
        layer.alert('该文件异常，请尝试删除并重新上传', {
            icon: 2,
            skin: 'layer-ext-moon'
        });
    }
    else {
        var index = layer.load(2);
        showFileSenResult(res);
        layer.close(index);
    }
}

//URL爬取并分词的异步逻辑部分
function crawlAndAnalyze() {

    var regex = /^https?:\/\/(([a-zA-Z0-9_-])+(\.)?)*(:\d+)?(\/((\.)?(\?)?=?&?[a-zA-Z0-9_-](\?)?)*)*$/i;
    var url = $('#input_url').val();
    //正则判断是否是链接
    if (!regex.test(url)) {
        layer.msg('这个不是URL，请检查。', {icon: 5});
        return;
    }
    //判断是否是本站的链接
    if (url.indexOf("/core/") != -1 || url.indexOf("localhost") != -1 || url.indexOf("127.") != -1) {
        layer.msg('这是我的网站，不要这么搞。', {icon: 5});
        return;
    }

    var obj = new Object();
    obj.url = url;
    var requestJson = JSON.stringify(obj);
    var index = layer.load(2);
    //发送异步请求
    jQuery.ajax({
        url: sen_url_path,
        type: "post",
        data: requestJson,
        dataType: "json",
        contentType: "application/json;charset=utf-8"
    }).done(function (res) {
        //关闭等待层
        layer.close(index);
        //如果正常返回
        if (res.status == 0) {
            showFileSenResult(res);
        }
        else {
            layer.alert('该网页异常，解析失败', {
                icon: 2,
                skin: 'layer-ext-moon'
            })
        }
    }).fail(function (data) {
        layer.close(index);
        layer.alert("请求失败，原因：" + data.msg, {icon: 2});
    });


}

/**
 *
 * 下面是API调用逻辑部分
 **/
//预览要API请求
function previewAPICode(formClassName) {

    //要发送的json对象
    var jsonObj = new Object();
    var tips = "";

    var form = $("." + formClassName);
    var sentenceType = form.find("select[name=\'sentenceType\']").val();
    var format_key = form.find("select[name=\'FormatIntroduce\']").val();
    var format_value = form.find("select[name=\'FORMAT\']").val();


    var selecter = "." + formClassName;
    var textArray = [];
    var textCount = $(selecter).find('.div_seg_api_text').length;
    var textGroup = $(selecter).find('.div_seg_api_text');
    var countTextNum = 0;
    //按文本数量来计算使用哪个接口
    if (textCount == 1) {
        var value = $(textGroup[0]).find('input[name=\'SEN_TEXT\']').val();
        if (value != "") {
            jsonObj.text = value;
            $(selecter).find('input[name=\'SEN_URL\']').val(sen_single_path);
            countTextNum++;
        }
    }
    else {
        for (var i = 0; i < textCount; i++) {

            var value = $(textGroup[i]).find('input[name=\'SEN_TEXT\']').val();
            if (value == "")
                continue;
            else {

                countTextNum++;
                var tmp = "";
                var key = "text";
                var obj = new Object();
                tmp = "{\"" + key + "\":\"" + value + "\"}";
                obj = $.parseJSON(tmp);
                textArray.push(obj);
            }
        }

        jsonObj.texts = textArray;

    }


    if (countTextNum == 0) {
        layer.alert("至少也要填一个需要句法分析的句子呀", {icon: 7});
        return "";
    }


    //处理已取得的属性
    if (sentenceType == null) {
        sentenceType = "HANLP_MaxEnt";
        tips += "您未选择句法分析方式，故使用默认值：<i style=\"color: #FF5722;\">HANLP_MaxEnt</i><br>"
    }
    if (format_key == null || format_value == null) {
        format_key = "format";
        format_value = "JSON";
        tips += "您未选择返回格式，故使用默认值：<i style=\"color: #FF5722;\">JSON</i><br>"
    }

    jsonObj.type = sentenceType;
    jsonObj.format = format_value;


    var jsonStr = JSON.stringify(jsonObj);
    var unformatStr = jsonStr;
    jsonStr = formatJson(jsonStr);

    var selecter = "." + formClassName;
    //放到请求代码框中
    $(selecter).find('.code-request').empty();
    $(selecter).find('.code-request').append(jsonStr);
    $('pre code').each(function (i, block) {
        hljs.highlightBlock(block);
    });

    //显示提示
    if (tips != "")
        layer.alert(tips, {icon: 7});

    return unformatStr;
}

//增加文本
function addAPITextInput(formClassName) {

    var selecter = "." + formClassName;
    if ($('.' + formClassName).find('.div_seg_api_text').length == 3) {
        layer.msg("3个够演示就好啦，别点了求求你");
        return;
    }

    var textGroup = $('.' + formClassName).find('.div_seg_api_text').parent();

    textGroup.append("<div class=\"layui-form-item div_seg_api_text\">" +
        "	<div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "		<select name=\"TextIntroduce\">" +
        "			<option value=\"\" disabled>句法分析文本</option>" +
        "			<option value=\"CT_FILTER\" selected=\"\">TEXT</option></select>" +
        "	</div>" +
        "	<div class=\"layui-input-inline\" style=\"width: 76%\">" +
        "		<input type=\"text\" name=\"SEN_TEXT\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"在这里输入您需要分析的文本，若要多段文本，请点击下面的添加按钮\" class=\"layui-input\" /></div>" +
        "	<div class=\"layui-input-inline\" style=\"width: 120px\">" +
        "		<div class=\"layui-btn-group\">" +
        "			<button type='button' class=\"layui-btn\" onclick='addAPITextInput(\"" + formClassName + "\")'>" +
        "				<i class=\"layui-icon\">&#xe654;</i></button>" +
        "			<button type='button' class=\"layui-btn layui-btn-warm layui-btn\" onclick='deleteAPITextInput(\"" + formClassName + "\",$(this))'>" +
        "				<i class=\"layui-icon\">&#xe640;</i></button>" +
        "		</div>" +
        "	</div>" +
        "</div>");

    layui.form.render();
    layui.element.init();

    //自动切换API的提示
    if ($('.' + formClassName).find('.div_seg_api_text').length > 1) {
        $(selecter).find('input[name=\'SEN_URL\']').val(sen_multiple_path);
        layer.tips('已自动切换多文本处理', selecter, {
            tips: 2
        });
    }

}


//删除文本
function deleteAPITextInput(formClassName, node) {


    var selecter = "." + formClassName;
    var nodeLength = $(selecter).find('.div_seg_api_text').length;
    if (nodeLength == 1) {
        layer.msg("你删了这最后1个我怎么演示啊？");
        return;
    }

    node.parent().parent().parent().remove();

    if (nodeLength == 2) {
        //自动切换API的提示
        $(selecter).find('input[name=\'SEN_URL\']').val(sen_single_path);
        layer.tips('已自动切换单文本处理API', selecter, {
            tips: 2
        });
    }
    layui.form.render();
    layui.element.init();
}


//发送请求
function sendRequest(formClassName) {
    var selecter = "." + formClassName;
    var requestJson = previewAPICode(formClassName);
    var requestObj = $.parseJSON(requestJson);
    var index = layer.load(2);
    var url;
    if ($(selecter).find('.div_seg_api_text').length == 1) url = sen_single_path;
    else url = sen_multiple_path;
    var rFormat = "";
    if (requestObj.format == 'JSON') rFormat = "json";
    else rFormat = "text"
    //发送异步请求
    jQuery.ajax({
        url: url,
        type: "post",
        data: requestJson,
        dataType: rFormat,
        contentType: "application/json;charset=utf-8"
    }).done(function (data) {
        //关闭等待层
        layer.close(index);

        if (requestObj.format == 'JSON') {

            if (data.status != 0) {
                layer.alert("请求失败，原因：" + data.msg, {icon: 2});
                return;
            }
            //填充code
            var jsonStr = JSON.stringify(data);

            jsonStr = formatJson(jsonStr);
            $(selecter).find('.code-response').empty();
            $(selecter).find('.code-response').removeClass("xml");
            $(selecter).find('.code-response').removeClass("json");
            $(selecter).find('.code-response').addClass("json");
            $(selecter).find('.code-response').append(jsonStr);
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }
        else if (requestObj.format == 'XML') {

            var xmlStr = formatXml(data.toString());
            $(selecter).find('.code-response').empty();
            $(selecter).find('.code-response').removeClass("xml");
            $(selecter).find('.code-response').removeClass("json");
            $(selecter).find('.code-response').addClass("xml");
            $(selecter).find('.code-response').text(xmlStr);
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }
        else if (requestObj.format == 'TEXT') {
            var textStr = formatXml(data.toString());
            $(selecter).find('.code-response').empty();
            $(selecter).find('.code-response').removeClass("xml");
            $(selecter).find('.code-response').removeClass("json");
            $(selecter).find('.code-response').addClass("xml");
            $(selecter).find('.code-response').text(textStr);
            $('pre code').each(function (i, block) {
                hljs.highlightBlock(block);
            });
        }

    }).fail(function (data) {
        layer.close(index);
        layer.alert("请求失败，原因：" + data.msg, {icon: 2});
    });


}


//获取要新添加的apiTAB内容
function getAnewAPITab(className) {


    return "    <fieldset class=\"layui-elem-field layui-field-title\">" +
        "      <legend>参数填充区域</legend>" +
        "      <div class=\"layui-field-box\">" +
        "        <div class=\"layui-row\">" +
        "          <div class=\"layui-col-md12\">" +
        "            <form class=\"layui-form " + className + "\" action=\"\">" +
        "<div class=\"layui-form-item\">" +
        "  <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "    <select name=\"method\">" +
        "      <option value=\"\" disabled>请求方法</option>" +
        "      <option value=\"post\" selected=\"\">POST</option>" +
        "      <option value=\"get\" disabled>GET</option>" +
        "      <option value=\"put\" disabled>PUT</option>" +
        "      <option value=\"delete\" disabled>DELETE</option></select>" +
        "  </div>" +
        "  <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "    <input type=\"text\" name=\"SEN_URL\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"/api/sen/singleness\" class=\"layui-input\" disabled></div>" +
        "</div>" +
        "<div class=\"layui-form-item\">" +
        "  <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "    <select name=\"sentenceTypeIntroduce\">" +
        "      <option value=\"\" disabled>句法分析方式</option>" +
        "      <option value=\"SenType\" selected=\"\">Type</option></select>" +
        "  </div>" +
        "  <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "    <select name=\"sentenceType\">" +
        "      <option value=\"\" disabled>目前系统内置的句法分析方法</option>" +
        "      <option value=\"HANLP_CRF\" selected=\"\">HANLP_CRF方式</option>" +
        "      <option value=\"HANLP_NeuralNetwork\" selected=\"\">HANLP_NeuralNetwork方式</option>" +
        "      <option value=\"HANLP_MaxEnt\" selected=\"\">HANLP_MaxEnt方式</option></select>" +
        "  </div>" +
        "</div>" +
        "<div class=\"layui-form-item\">" +
        "  <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "    <select name=\"FormatIntroduce\">" +
        "      <option value=\"\" disabled>格式选择</option>" +
        "      <option value=\"FORMAT\" selected=\"\">FORMAT</option></select>" +
        "  </div>" +
        "  <div class=\"layui-input-block\" style=\"width: 91%\">" +
        "    <select name=\"FORMAT\">" +
        "      <option value=\"\" disabled>目前已经支持的返回格式</option>" +
        "      <option value=\"JSON\" selected=\"\">JSON</option>" +
        "      <option value=\"XML\">XML</option>" +
        "      <option value=\"TEXT\">TEXT</option></select>" +
        "  </div>" +
        "</div>" +
        "              <div class=\"layui-form-item div_seg_api_text\">" +
        "                <div class=\"layui-input-inline\" style=\"width: 100px;\">" +
        "                  <select name=\"TextIntroduce\">" +
        "                    <option value=\"\" disabled>分词文本</option>" +
        "                    <option value=\"CT_FILTER\" selected=\"\">TEXT</option></select>" +
        "                </div>" +
        "                <div class=\"layui-input-inline\" style=\"width: 76%\">" +
        "                  <input type=\"text\" name=\"SEN_TEXT\" lay-verify=\"title\" autocomplete=\"off\" placeholder=\"在这里输入您需要进行分析的文本，若要多段文本，请点击下面的添加按钮\" class=\"layui-input\" /></div>" +
        "                <div class=\"layui-input-inline\" style=\"width: 120px\">" +
        "                  <div class=\"layui-btn-group\">" +
        "                    <button type=\'button\' id=\"btn_add_onlyone\" class=\"layui-btn layui-btn\" onclick=\'addAPITextInput(\"" + className + "\")\'>" +
        "                      <i class=\"layui-icon\">&#xe654;</i></button>" +
        "                    <button type=\'button\' id=\"btn_delete_onlyone\" class=\"layui-btn layui-btn-warm layui-btn\" onclick=\'deleteAPITextInput(\"" + className + "\",$(this))\'>" +
        "                      <i class=\"layui-icon\">&#xe640;</i></button>" +
        "                  </div>" +
        "                </div>" +
        "              </div>" +
        "            </form>" +
        "            <fieldset class=\"layui-elem-field layui-field-title\">" +
        "              <legend>执行操作</legend>" +
        "              <div class=\"layui-field-box\">" +
        "                <div class=\"layui-btn-container\">" +
        "                  <button class=\"layui-btn layui-btn-primary\" onclick=\'previewAPICode(\"" + className + "\")\'>" +
        "                    <i class=\"layui-icon\">&#xe62a;</i>预览请求</button>" +
        "                  <button class=\"layui-btn layui-btn-normal\" onclick=\'sendRequest(\"" + className + "\")\'>" +
        "                    <i class=\"layui-icon\">&#xe609;</i>发送请求</button>" +
        "                  <button type=\"reset\" class=\"layui-btn layui-btn-warm\">" +
        "                    <i class=\"layui-icon\">&#xe640;</i>重置请求</button></div>" +
        "              </div>" +
        "            </fieldset>" +
        "            <fieldset class=\"layui-elem-field layui-field-title " + className + "\">" +
        "              <legend>请求预览与分词结果</legend>" +
        "              <div class=\"layui-field-box\">" +
        "                <div class=\"layui-row\">" +
        "                  <div class=\"layui-col-md6\" style=\"min-height: 600px\">" +
        "                    <fieldset class=\"layui-elem-field\">" +
        "                      <legend>请求-REQUEST</legend>" +
        "                      <div class=\"layui-field-box\">" +
        "                        <pre>" +
        "                          <code class=\"json hljs code-request\" style=\"    line-height: 30px; margin-left: 30px;word-wrap: break-word; max-width: 480px; height: 600px;overflow-y: scroll;\"></code>" +
        "                        </pre>" +
        "                      </div>" +
        "                    </fieldset>" +
        "                  </div>" +
        "                  <div class=\"layui-col-md6\" style=\"min-height: 600px;\">" +
        "                    <fieldset class=\"layui-elem-field\">" +
        "                      <legend>响应-RESPONSE</legend>" +
        "                      <div class=\"layui-field-box\">" +
        "                        <pre>" +
        "                          <code class=\"json hlsj code-response\" style=\" line-height: 30px; margin-left: 30px;word-wrap: break-word; max-width: 480px; height: 600px;overflow-y: scroll;\"></code>" +
        "                        </pre>" +
        "                      </div>" +
        "                    </fieldset>" +
        "                  </div>" +
        "                </div>" +
        "              </div>" +
        "            </fieldset>" +
        "          </div>" +
        "        </div>" +
        "      </div>" +
        "    </fieldset>";

}